#!/usr/bin/bash

SVC_NAME="svc:/pkgsrc/openldap-server:default"

gsed -i '/core.schema/a\include         /opt/local/etc/openldap/schema/cosine.schema \
include         /opt/local/etc/openldap/schema/nis.schema \
include         /opt/local/etc/openldap/schema/inetorgperson.schema' /opt/local/etc/openldap/slapd.conf

ARG_NAME=ldap_suffix
if /usr/sbin/mdata-get ${ARG_NAME} 1>/dev/null 2>&1; then
    ARG_VALUE=$(/usr/sbin/mdata-get ${ARG_NAME})
    gsed -i "s/^suffix.*/suffix          \"${ARG_VALUE}\"/g" /opt/local/etc/openldap/slapd.conf   
fi

ARG_NAME=ldap_rootdn
if /usr/sbin/mdata-get ${ARG_NAME} 1>/dev/null 2>&1; then
    ARG_VALUE=$(/usr/sbin/mdata-get ${ARG_NAME})
    gsed -i "s/^rootdn.*/rootdn          \"${ARG_VALUE}\"/g" /opt/local/etc/openldap/slapd.conf   
fi

ARG_NAME=ldap_rootpw
if /usr/sbin/mdata-get ${ARG_NAME} 1>/dev/null 2>&1; then
    ARG_VALUE=$(/usr/sbin/mdata-get ${ARG_NAME})
    ARG_VALUE=$(slappasswd -s ${ARG_VALUE})
    gsed -i "s|^rootpw.*|rootpw          ${ARG_VALUE}|g" /opt/local/etc/openldap/slapd.conf   
fi

# Enable openldap smf service
svcadm enable ${SVC_NAME}